package top.xunfong.satoken.util;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaStorage;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import top.xunfong.common.core.domain.model.LoginUserInfo;

/**
 * @author: xunfong
 * @date: 2025/10/18 3:54
 */
public class LoginHelper {

    public static final String LOGIN_USER_KEY = "loginUser";
    public static final String USER_KEY = "userId";


    /**
     * 登陆
     *
     * @param userInfo
     */
    public static void login(LoginUserInfo userInfo) {
        SaStorage storage = SaHolder.getStorage();
        storage.set(LOGIN_USER_KEY, userInfo);
        storage.set(USER_KEY, userInfo.getUserId());
        StpUtil.login(userInfo.getUserId());
        StpUtil.getTokenSession().set(LOGIN_USER_KEY, userInfo);
    }

    /**
     * 获取登陆用户信息
     * 在redis中获取数据，并写入上下文
     *
     * @return
     */
    public static LoginUserInfo getLoginUserInfo() {
        // 直接去缓存中获取
        LoginUserInfo userInfo = (LoginUserInfo) SaHolder.getStorage().get(LOGIN_USER_KEY);
        if (ObjectUtil.isNotNull(userInfo)) {
            return userInfo;
        }
        SaSession tokenSession = StpUtil.getTokenSession();
        if (ObjectUtil.isNotNull(tokenSession)) {
            userInfo = (LoginUserInfo) tokenSession.get(LOGIN_USER_KEY);
            SaHolder.getStorage().set(LOGIN_USER_KEY, userInfo);
        }
        return userInfo;
    }

}
